package cn.ywang.register;

import cn.ywang.config.ZKConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @Auther: BeatificWang
 * @Date: 2018/12/12 0:00
 */
public class RegisterCenter implements IRegisterCenter {

	private CuratorFramework framework;

	{
		this.framework = CuratorFrameworkFactory
				                 .builder()
				                 .connectString(ZKConfig.CONNECT_STRING)
				                 .sessionTimeoutMs(40000)
				                 .retryPolicy(new ExponentialBackoffRetry(3000, 10))
				                 .build();
		this.framework.start();
	}

	@Override
	public void register(String serviceName, String serviceAddress) {
		String servicePath = ZKConfig.REGISTRY_PATH + "/" + serviceName;
		try {
			if (this.framework.checkExists().forPath(servicePath) == null) {
				this.framework.create()
						.creatingParentsIfNeeded()
						.withMode(CreateMode.PERSISTENT)
						.forPath(servicePath, "1".getBytes());
			}
			String addressPath = servicePath + "/" + serviceAddress;
			String node = this.framework.create()
					              .withMode(CreateMode.EPHEMERAL)
					              .forPath(addressPath, "0".getBytes());
			System.out.println("服务注册成功:" + node);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
